<script>
    import {location, querystring} from 'svelte-spa-router'
    import List from '../components/list.svelte';
    import Btn from '../components/btn.svelte';
    import Select from '../components/select.svelte';
    import Paging from '../components/paging.svelte';
    import QueryBar from '../components/queryBar.svelte';
    import { onMount } from 'svelte';
    import { Post } from '../lib/net.js';
    import { SearchAgent,ActiveFreezeUser,AgentUsersList,AgentList } from '../api.js';
    import Query from '../model/query.js';
    import moment from 'moment';

    let btnText = `<i>+</i>添加代理`
    let btnHref = "/agent/add"

    let data = {title:[ "UID","姓名","手机号","邮箱","身份证","代理人姓名","开单数量","账户资金","加入时间","状态" ],data:[],daochu:[]}
	
	

    let query = new Query();

    // 向列表赛数据，须先定义表头，拿到数据后做title下表映射关系.

    onMount(()=>{
        getList();
		
    });

    async function getList(e){

        if (e) {
            query.start = e.detail.start
            query.end = e.detail.end
            if (e.detail.types !== 1) {
                
                let ret = await Post(SearchAgent, {
                    type: e.detail.types,
                    condition: query.condition,
                });
                query.condition = "";
                query.admin = ret
                if(query.admin == -100) return
                // query.admin = '18'
            }
        }
       let ret = await Post(AgentUsersList,query)

       query.total = ret.total;
       query.size = ret.size;
       query.page = ret.page;
       let _data = [];
       for(let item of ret.list) {
        let balance = 0;
        balance += Number(item.assets.balance.balance)
        balance += Number(item.assets.contract.balance)
         let arr = [item.id,item.userinfo.name,item.phone,item.email,item.userinfo.id,item.inviteCode,item.orderCount,balance.toFixed(2),item.userinfo.show_create_date,`<select on:click><option value=0>正常</option><option ${item.state == 1 && 'selected'} value=1>冻结</option></select>`
         ];
		 
         arr.id = item.id;
         arr.handler = changeState
        _data.push(arr);
       }
        data.data = _data;
		
		
		
    }
	
	async function getDaochuList(){
		const notification= document.querySelector(".notification");
		notification.style.display="block"
		notification.innerHTML="数据量较大，请勿重复点击，稍等一会~~~"
		
	   const daochuQuery={
		   condition:query.condition,
		   end:query.end,
		   page:1,
		   size:query.total,
		   start:query.start,
		   total:query.total,
		   type:query.type,
		   types:query.types
	   };
	   let ret = await Post(AgentUsersList,daochuQuery)
	   let arrDaochu = [];
	   for(let item of ret.list) {
	    let balance = 0;
	    balance += Number(item.assets.balance.balance)
	    balance += Number(item.assets.contract.balance)
		 let arrDaochus = [item.id,item.userinfo.name,item.phone,item.email,item.userinfo.id,item.inviteCode,item.orderCount,balance.toFixed(2),item.userinfo.show_create_date,item.state == 1?'冻结':'正常'];
		arrDaochu.push(arrDaochus)
	   }
		data.daochu = arrDaochu;
		
		
		notification.innerHTML="操作成功"
		notification.style.display="none"
		
		    
		tableToExcel()
	}

    async function changeState(){
        event.stopPropagation()
        let _select = this.querySelector("select");
        let id = this.getAttribute("data-id");

        await Post(ActiveFreezeUser,{id: Number(id)});
        getList();
    }


    function setPage(page){
        query.page = page;
        getList();
    }
	
	
	function tableToExcel(){
	  //要导出的json数据
	  const jsonData = data.daochu;
	  //列标题，逗号隔开，每一个逗号就是隔开一个单元格
	   let str= data.title.toString()+'\n'
	  //增加\t为了不让表格显示科学计数法或者其他格式
	  for(let i = 0 ; i < jsonData.length ; i++ ){
	    for(let item in jsonData[i]){
	        str+=`${jsonData[i][item] + '\t'},`;     
	    }
	    str+='\n';
	  }
	  //encodeURIComponent解决中文乱码
	  let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
	  //通过创建a标签实现
	  let link = document.createElement("a");
	  link.href = uri;
	  //对下载的文件命名
	  link.download =  "会员信息.csv";
	  document.body.appendChild(link);
	  link.click();
	  document.body.removeChild(link);
	}
</script>

<div class="view">
    <div style="display: flex;flex-direction: row;align-items: center;width: 99%;margin: 5px;height: 60px;background-color: white;margin-top: 5px;justify-content: space-between;padding: 0 10px;"
         class="borderRadius4">
        <span style="color: #20222A;margin: 20px">
            会员信息
        </span> 
		<a style="display: none;" class="button is-warning is-small" on:click={getDaochuList}>导出会员信息</a>
    </div>
    <div class=" borderRadius4 container">
        <div class="columns rowReverse" >
            <div class="column is-4">
                <div class="rowNumCenter">
                    <span class="left1">用户总数：</span>
                    <span class="mid1" style="color:forestgreen">{query.total}</span>
                    <span class="left1">人</span>
                </div>
            </div>
        </div>
    </div>
    <div class="borderRadius4 container rowCenter ">
        <QueryBar query={query} on:message={getList}/>
    </div>
    <div class="container" style="margin-top: -10px">
        <List data={data}/>
    </div>
    <div class="container rowReverse">
        {#if query.total !== 0}
        <Paging page={query} handler={setPage}/>
        {/if}
    </div>
	
	
	<div class="modal">
	  <div class="modal-background"></div>
	  <div class="modal-content">
	     Any other Bulma elements you want 
	  </div>
	  <button class="modal-close is-large" aria-label="close"></button>
	</div>
</div>

<style>
    .borderRadius4{
        border-radius: 4px;
    }
    .container {
        margin:20px 5px;
    }
    .info {
        background: #fff;
    }
    .btn {
        line-height: 5px;
        top: 50%;
        transform: translateY(10%);
    }
    .rowNumCenter{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-end;
        font-size: 12px;
    }
</style>
